package models

import (
	"go-admin-official/modules/database"
)

type AccountLogModel struct {
	Base `json:"-"`

	Id        int64  `json:"id"`
	UserId    int64  `json:"user_id"`
	Amount    int64  `json:"amount"`
	Balance   int64  `json:"balance"`
	Type      int64  `json:"type"`
	CreatedAt string `json:"created_at"`
	UpdatedAt string `json:"updated_at"`
}

func AccountLog() AccountLogModel {
	return AccountLogModel{Base: Base{Table: "account_log"}}
}

func (t AccountLogModel) WithTx(tx *database.SqlTx) AccountLogModel {
	t.Tx = tx
	return t
}

func (t AccountLogModel) Find(id interface{}) AccountLogModel {
	item, _ := database.Table(t.Table).Find(id)

	if item == nil {
		return AccountLog()
	}

	return t.MapToModel(item)
}

func (t AccountLogModel) Update(key string, value interface{}) (int64, error) {
	return database.Table(t.Table).
		Where("id", "=", t.Id).
		Update(database.H{
			key: value,
		})
}

const (
	AccountLogTypeBuyPlugin = 1
	AccountLogTypeBuyTheme  = 2
)

func (t AccountLogModel) InsertBuyPluginLog(userId, balance, amount int64) error {
	_, err := database.SetTx(t.Tx).Table(t.Table).
		Insert(database.H{
			"user_id": userId,
			"amount":  amount,
			"balance": balance,
			"type":    AccountLogTypeBuyPlugin,
		})
	return err
}

func (t AccountLogModel) InsertBuyThemeLog(userId, balance, amount int64) error {
	_, err := database.SetTx(t.Tx).Table(t.Table).
		Insert(database.H{
			"user_id": userId,
			"amount":  amount,
			"balance": balance,
			"type":    AccountLogTypeBuyTheme,
		})
	return err
}

func (t AccountLogModel) IsEmpty() bool {
	return t.Id == int64(0)
}

func (t AccountLogModel) IsNotEmpty() bool {
	return t.Id != int64(0)
}

func (t AccountLogModel) MapToModel(m map[string]interface{}) AccountLogModel {
	t.Id, _ = m["id"].(int64)
	t.UserId, _ = m["user_id"].(int64)
	t.Amount, _ = m["amount"].(int64)
	t.Balance, _ = m["balance"].(int64)
	t.Type, _ = m["type"].(int64)
	t.CreatedAt, _ = m["created_at"].(string)
	t.UpdatedAt, _ = m["updated_at"].(string)
	return t
}
